package com.ibm.pess.rest.resources;

import static org.junit.Assert.assertNotNull;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.rest.common.api.ActivitiUtil;
import org.activiti.rest.common.api.SecuredResource;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.restlet.data.MediaType;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Post;

import com.ibm.pess.order.Order;

public class CloseOrderRestResource extends SecuredResource {

	private static Logger log = Logger.getLogger("log");

	@Post
	public Representation post(Representation entity) {
		JSONObject resp = new JSONObject();
		try {
			// JsonRepresentation data = new JsonRepresentation(entity);
			// JSONObject requestParms = data.getJsonObject();
			// log.info("CloseOrderRestResource requestParms:"
			// + requestParms.toString());

			ProcessEngine pe = ActivitiUtil.getProcessEngine();
			RuntimeService runtimeService = pe.getRuntimeService();
			List<ProcessInstance> pis = runtimeService
					.createProcessInstanceQuery().includeProcessVariables()
					.active().processDefinitionKey("logistic-demo").list();
			for (ProcessInstance pi : pis) {
				try {
					Order od = (Order) pi.getProcessVariables().get("order");
					od.load();
					TaskService taskService = pe.getTaskService();
					Task courierTask;
					Task receiverTask;
					courierTask = taskService.createTaskQuery()
							.taskAssignee("gonzo").singleResult();
					if (courierTask != null) {
						taskService.claim(courierTask.getId(), "gonzo");
						taskService.complete(courierTask.getId());
						od.setStatus("Checked in Inventory Staff");
						od.update();
						log.info(String.format("Complete order %s by %s",
								od.getId(), "courier"));
					} else {
						receiverTask = taskService.createTaskQuery()
								.taskAssignee("fozzie").singleResult();
						if (receiverTask != null) {
							taskService.claim(receiverTask.getId(), "fozzie");
							taskService.complete(receiverTask.getId());
							od.setLoc("receiver's site");
							od.setStatus("closed");
							od.update();
							log.info(String.format("Complete order %s by %s",
									od.getId(), "receiver"));
							log.info("order closed.");
						}
					}
				} catch (Exception e) {
					log.error("no order in process instance " + pi.getId());
				}
			}
		} catch (Exception e) {
			log.error("CloseOrderRestResource error :" + e.toString());
			return new StringRepresentation(
					"{\"rc\":\"1\",\"reason\":\"empty in body\"}",
					MediaType.APPLICATION_JSON);
		}
		return new StringRepresentation(resp.toString(),
				MediaType.APPLICATION_JSON);

	}
}
